package org.example;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLOutput;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        //获取文件
        String filePath = "C:\\Users\\Yong_Z\\Desktop\\GenshinDispatch_Demo\\src\\main\\java\\org\\example\\OSRELAndroid3.4.0.json"; // 文件路径

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            StringBuilder jsonContent = new StringBuilder();
            while ((line = br.readLine()) != null) {
                jsonContent.append(line);
            }
            String jsonData = jsonContent.toString();
            // 在这里处理读取到的 JSON 数据
            //System.out.println(jsonData);
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONObject json = jsonObject.getJSONObject("region_info");
            String DataUrl = json.getString("data_url");
            String ResourceUrl = json.getString("resource_url");
            int lastIndex = DataUrl.lastIndexOf("/");
            String DataUrlBak = DataUrl.substring(lastIndex + 1);
            int ClientDataVersion = json.getInt("client_data_version");
            int ClientSilenceDataVersion = json.getInt("client_silence_data_version");
            String ClientVersionSuffix = json.getString("client_version_suffix");
            String ClientSilenceVersionSuffix = json.getString("client_silence_version_suffix");
            String ClientDataMd5 = json.getString("client_data_md5");
            String ClientSilenceDataMd5 = json.getString("client_silence_data_md5");
            System.out.println();
            System.out.println("DataUrlBak: " + DataUrlBak);
            System.out.println("ResourceUrlBak: " + DataUrlBak);
            System.out.println("DataUrl: " + DataUrl);
            System.out.println("ResourceUrl: " + ResourceUrl);
            System.out.println("ClientDataVersion: " + ClientDataVersion);
            System.out.println("ClientSilenceDataVersion: " + ClientSilenceDataVersion);
            System.out.println("ClientVersionSuffix: " + ClientVersionSuffix);
            System.out.println("ClientSilenceVersionSuffix: " + ClientSilenceVersionSuffix);
            System.out.println("ClientDataMd5: " + ClientDataMd5);
            System.out.println("ClientSilenceDataMd5: " + ClientSilenceDataMd5);
            System.out.println();
            JSONObject ResVersionConfig = json.getJSONObject("res_version_config");
//            boolean Relogin = ResVersionConfig.getBoolean("Relogin");
            boolean Relogin = false;
            int Version = ResVersionConfig.getInt("version");
            String VersionSuffix = ResVersionConfig.getString("version_suffix");
            String Branch = ResVersionConfig.getString("branch");
            String ReleaseTotalSize = ResVersionConfig.getString("release_total_size");
            String download_ResourceUrl = ResourceUrl + "/output_" + Version + "_" + VersionSuffix + "/client/Android/";
            System.out.println(download_ResourceUrl);
            String Md5 = ResVersionConfig.getString("md5");
//            System.out.println(Md5);
            URL url = new URL(DOWNLOAD_ADDRESS);
//             下载path
            String path = url.getPath();
            // 获得签名后的链接
            String signedUrl = getSignedUrl(path);
            System.out.println(signedUrl);
            Pattern pattern = Pattern.compile("https://vip\\.123pan\\.cn(/.+)$");
            Matcher matcher = pattern.matcher(signedUrl);
            if (matcher.find()) {
                String subString = matcher.group(1);
                System.out.println(subString);
            }
            String[] lines = Md5.split("\n");
            StringBuilder newMd5 = new StringBuilder();
            for (String str_line : lines) {
                JSONObject json_obj = new JSONObject(str_line);
                String remoteName = json_obj.getString("remoteName");
                // 将md5中的remoteName 替换为remoteName +"?auth_key=" + Main.getAuth(ResourceUrl)
                String newRemoteName = remoteName + signedUrl;
                json_obj.put("remoteName", newRemoteName);
                // 获取修改后的字符串
                String modifiedLine = json_obj.toString();
                newMd5.append(modifiedLine);
//                System.out.println(modifiedLine);
            }
            System.out.println(newMd5);



//            System.out.println("Relogin: " + Relogin);
//            System.out.println("Version: " + Version);
//            System.out.println("VersionSuffix: " + VersionSuffix);
//            System.out.println("Branch: " + Branch);
//            System.out.println("ReleaseTotalSize: " + ReleaseTotalSize);
//            System.out.println("Md5: " + Md5);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static StringBuilder modify(String url, String text) throws MalformedURLException {
        String[] lines = text.split("\n");
        StringBuilder newMd5 = new StringBuilder();
        for (String str_line : lines) {
            JSONObject json_obj = new JSONObject(str_line);
            String remoteName = json_obj.getString("remoteName");
            // 将md5中的remoteName 替换为remoteName +"?auth_key=" + Main.getAuth(ResourceUrl)
            URL downloadUrl = new URL(url + remoteName);
            // 下载path
            String path = downloadUrl.getPath();
            // 获得签名后的链接
            String signedUrl = getSignedUrl(path);
            String newRemoteName = remoteName + signedUrl;
            json_obj.put("remoteName", newRemoteName);
            // 获取修改后的字符串
            String modifiedLine = json_obj.toString();
            newMd5.append(modifiedLine);
        }
        return newMd5;
    }
    // 123云盘中设置的密钥
    private static final String PRIVATE_KEY = "123456";
    // 123云盘用户UID
    private static final long UID = 1813533250;
    // 防盗链过期时间间隔(秒)
    private static final long EXPIRED_TIME_SEC = 3 * 60;
    // 下载地址
    private static final String DOWNLOAD_ADDRESS = "https://vip.123pan.cn/1813533250/outputs/client_game_res/3.4_live/output_12591909_58182dc06f/client/Android/res_versions_external";

    private static String getSignedUrl(String path) {
        // 下载链接的过期时间戳（秒）
        long timestamp = new Date().getTime() / 1000 + EXPIRED_TIME_SEC;
        // 生成随机数（建议使用UUID，不能包含中划线（-））
        String randomUUID = UUID.randomUUID().toString().replaceAll("-", "");
        // 待签名字符串="URI-timestamp-rand-uid-PrivateKey" (注:URI是用户的请求对象相对地址，不包含参数)
        String unsignedStr = String.format("%s-%d-%s-%d-%s", path, timestamp, randomUUID, UID, PRIVATE_KEY);
        System.out.println(DOWNLOAD_ADDRESS + "?auth_key=" + String.format("%d-%s-%d-", timestamp, randomUUID, UID) + md5sum(unsignedStr));
        return "?auth_key=" + String.format("%d-%s-%d-", timestamp, randomUUID, UID) + md5sum(unsignedStr);
    }

    // MD5加密
    private static String md5sum(String unsignedStr) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] secretBytes = md5.digest(unsignedStr.getBytes());
            return bytesToHex(secretBytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    // 二进制转为十六进制字符串
    public static String bytesToHex(byte[] bytes) {
        StringBuilder md5str = new StringBuilder();
        // 把数组每一字节换成16进制连成md5字符串
        int digital;
        for (byte aByte : bytes) {
            digital = aByte;

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString().toLowerCase();
    }
}
